package com.im.app.processor;

import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.exception.ImException;
import org.jim.core.http.HttpRequest;
import org.jim.core.packets.Command;
import org.jim.core.packets.LoginReqBody;
import org.jim.server.JimServerAPI;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.LoginReqHandler;
import org.jim.server.processor.handshake.WsHandshakeProcessor;


public class JIMWsHandshakeProcessor extends WsHandshakeProcessor {

    @Override
    public void onAfterHandshake(ImPacket packet, ImChannelContext imChannelContext) throws ImException {
        LoginReqHandler loginHandler = (LoginReqHandler) CommandManager.getCommand(Command.COMMAND_LOGIN_REQ);
        HttpRequest request = (HttpRequest)packet;
        String userId = request.getParams().get("userId") == null ? null : (String)request.getParams().get("userId")[0];
        String token = request.getParams().get("token") == null ? null : (String)request.getParams().get("token")[0];
        String type = request.getParams().get("type") == null ? null : (String)request.getParams().get("type")[0];
        if(userId == null || token == null || type == null){
            JimServerAPI.remove(imChannelContext,"login error");
            return;
        }

        LoginReqBody loginBody = new LoginReqBody(userId,"",token);
        loginBody.setType(Integer.parseInt(type));

        ImPacket loginRespPacket = loginHandler.wsLogin(loginBody, imChannelContext);
        if(loginRespPacket != null){
            JimServerAPI.send(imChannelContext, loginRespPacket);
        }
    }
}
